package com.wyix.controller;

import com.wyix.service.AuthService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wangdx
 * @since 2025/8/20
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private AuthService authService;

    /**
     * 用户登录，获取Token
     */
    @PostMapping("/login")
    public Map<String, String> login(@RequestParam String username, @RequestParam String password) {
        // 实际项目中应该验证用户名密码
        // 这里简化处理，直接生成Token
        String token = authService.generateToken(username);
        String refreshToken = authService.generateRefreshToken(username);

        Map<String, String> result = new HashMap<>();
        result.put("token", token);
        result.put("refreshToken", refreshToken);
        result.put("tokenType", "Bearer");

        return result;
    }

    /**
     * 刷新Token
     */
    @PostMapping("/refresh")
    public Map<String, String> refresh(@RequestParam String refreshToken) {
        String newToken = authService.refreshToken(refreshToken);

        Map<String, String> result = new HashMap<>();
        result.put("token", newToken);
        result.put("tokenType", "Bearer");

        return result;
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public Map<String, String> getCurrentUser(HttpServletRequest request) {
        // 从请求属性中获取当前用户
        String username = (String) request.getAttribute("currentUser");

        Map<String, String> result = new HashMap<>();
        result.put("username", username);
        return result;
    }
}
